<template>
  <div>
    <el-tabs v-model="activeName" @tab-click="handleClick" style="margin-left: 50px; margin-right: 50px">
      <el-tab-pane label="基本信息" name="first">
        <el-form ref="form" :model="form" label-width="80px">
<!--          <el-form-item label="商品分类">-->
<!--            <el-select v-model="form.goods.category1Id" placeholder="请选择一级分类">-->
<!--              <el-option-->
<!--                v-for="item in category1List"-->
<!--                :key="item.id"-->
<!--                :label="item.name"-->
<!--                :value="item.id">-->
<!--              </el-option>-->
<!--            </el-select>-->

<!--            <el-select v-model="form.goods.category2Id" placeholder="请选择二级分类">-->
<!--              <el-option-->
<!--                v-for="item in category2List"-->
<!--                :key="item.id"-->
<!--                :label="item.name"-->
<!--                :value="item.id">-->
<!--              </el-option>-->
<!--            </el-select>-->

<!--            <el-select v-model="form.goods.category3Id" placeholder="请选择三级分类">-->
<!--              <el-option-->
<!--                v-for="item in category3List"-->
<!--                :key="item.id"-->
<!--                :label="item.name"-->
<!--                :value="item.id">-->
<!--              </el-option>-->
<!--            </el-select>-->

<!--            模版ID：{{form.goods.typeTemplateId}}-->


<!--          </el-form-item>-->

          <el-form-item label="商品分类">
            <el-cascader
              style="width: 40%"
              v-model="value"
              :options="options"
              :props="{'label':'name','value':'id'}"
            ></el-cascader>

            模版ID：{{form.goods.typeTemplateId}}
          </el-form-item>

          <el-form-item label="商品名称">
            <el-input v-model="form.goods.goodsName" style="width: 50%"></el-input>
          </el-form-item>
          <el-form-item label="商品品牌">
            <el-select v-model="form.goods.brandId" placeholder="请选择品牌" style="width: 50%">
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.text"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="副标题">
            <el-input v-model="form.goods.caption" style="width: 50%"></el-input>
          </el-form-item>
          <el-form-item label="商品价格">
            <el-input v-model="form.goods.price" style="width: 50%">
              <template slot="prepend">¥</template>
            </el-input>
          </el-form-item>
          <el-form-item label="商品简介">
            <editor v-model="form.goodsDesc.introduction" :min-height="192" style="width: 50%"/>
          </el-form-item>
          <el-form-item label="包装列表">
            <el-input type="textarea" v-model="form.goodsDesc.packageList" style="width: 50%"></el-input>
          </el-form-item>
          <el-form-item label="售后服务">
            <el-input type="textarea" v-model="form.goodsDesc.saleService" style="width: 50%"></el-input>
          </el-form-item>
        </el-form>

      </el-tab-pane>
      <el-tab-pane label="商品图片" name="second">
        <el-button type="primary" @click="dialogVisible = true,image={},imageUrl=''">上传图片</el-button>
        <el-table
          :data="imageList"
          border
          style="width: 100%">
          <el-table-column
            prop="color"
            label="颜色">
          </el-table-column>
          <el-table-column
            prop="url"
            label="图片">

            <template slot-scope="scope">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.url"
                fit="contain"></el-image>
            </template>

          </el-table-column>
          <el-table-column
            label="操作"
            width="180px">
            <template slot-scope="scope">
              <el-button type="danger" @click="removeImg(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog
          title="图片上传"
          :visible.sync="dialogVisible"
          width="50%">


          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="颜色">
              <el-input v-model="image.color"></el-input>
            </el-form-item>
            <el-form-item label="图片">
              <el-upload
                class="avatar-uploader"
                action="/dev-api/cms/goods/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :headers="{'Authorization':token}">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-form>


          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveImage">确 定</el-button>
          </span>
        </el-dialog>

      </el-tab-pane>
      <el-tab-pane label="拓展属性" name="third">

        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item :label="item.text" :key="item.text" v-for="item in customAttributeItemsList">
            <el-input v-model="item.value"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="商品规格" name="fourth">
        <el-form ref="form" :model="form" label-width="180px">
          <el-form-item label="是否启用规格">
            <el-checkbox true-label="1" false-label="0" v-model="form.goods.isEnableSpec"/>
          </el-form-item>
        </el-form>


        <el-form ref="form" :model="form" label-width="180px" v-show="form.goods.isEnableSpec==1">
          <el-form-item :label="spec.text" :key="spec.id" v-for="spec in specList">
            <el-checkbox @change="selectOption(spec.text,option.optionName)" :label="option.optionName" name="type" :key="option.id" v-for="option in specOptionsMap[spec.id]" ></el-checkbox>
          </el-form-item>
        </el-form>

        <el-table
          :data="items"
          border
          v-show="form.goods.isEnableSpec==1"
          style="width: 100%">

          <el-table-column
            v-for="spec in specificationItems"
            :key="spec.attributeName"
            :label="spec.attributeName">

            <template slot-scope="scope">
              {{scope.row.spec[spec.attributeName]}}
            </template>

          </el-table-column>


          <el-table-column
            label="价格">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="库存">
            <template slot-scope="scope">
              <el-input v-model="scope.row.num"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="是否启用"
            width="80">
            <template slot-scope="scope">
              <el-checkbox true-label="1" false-label="0" v-model="scope.row.status"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column
            label="是否默认"
            width="80">
            <template slot-scope="scope">
              <el-checkbox true-label="1" false-label="0" v-model="scope.row.isDefault"></el-checkbox>
            </template>
          </el-table-column>
        </el-table>

      </el-tab-pane>
    </el-tabs>

    <hr style="margin-left: 50px; margin-right: 50px"/>
    <el-button type="success" style=" margin-left: 50px" @click="save">保存</el-button>

  </div>
</template>

<script>
import { addGoods } from "@/api/cms/goods";
import { listCategory, getCategory, listTreeCategory } from "@/api/cms/category";
import { getTemplate } from "@/api/cms/template";
import { getSpecOptions } from "@/api/cms/spec";
import Cookies from "js-cookie";
import Template from '@/views/cms/template'

export default {
  components: { Template },
  data() {
    return {
      value: null,
      options:[],
      activeName: 'first',
      form:{
        goods:{
          goodsName:'',
          caption:'',
          price:0,
          category1Id:'',
          category2Id:'',
          category3Id:'',
          typeTemplateId:'',
          brandId:'',
          isEnableSpec:'0'
        },
        goodsDesc:{
          introduction:'',
          packageList:'',
          saleService:'',
          customAttributeItems: '',
          itemImages:'',
          specificationItems:''
        },
        items:[]
      },
      category1List:[],
      category2List:[],
      category3List:[],
      brandList:[],
      customAttributeItemsList:[],
      imageList:[],
      dialogVisible: false,
      imageUrl:'',
      token:'',
      image:{
        color:'',
        url:''
      },
      specList:[],
      specOptionsMap:{

      },
      specificationItems:[],
      items:[]
    };
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    save(){
      this.form.goodsDesc.customAttributeItems = JSON.stringify(this.customAttributeItemsList)
      this.form.goodsDesc.itemImages = JSON.stringify(this.imageList)
      this.form.goodsDesc.specificationItems = JSON.stringify(this.specificationItems)

      this.form.items = JSON.parse(JSON.stringify(this.items));

      for(var i in this.form.items){
        var item = this.form.items[i]
        item.spec = JSON.stringify(item.spec);
      }

      addGoods(this.form).then((res)=>{
        if(res.code == 200){
          this.$message.success(res.msg)
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);

      if(res.code == 200){
        this.image.url = res.data
      }else{
        this.$message.error(res.msg)
      }
    },
    saveImage(){
      this.imageList.push(this.image)
      this.dialogVisible = false
    },
    getOptions(id){
      getSpecOptions(id).then((res)=>{
        this.specOptionsMap[id] = res.data
      })
    },
    selectOption(specName,optionName){
      if(this.specificationItems.length == 0){
        //第一次选中
        this.specificationItems.push({"attributeName":specName,attributeValue:[optionName]})
        this.generateList();
        return;
      }
      //数组中原本就有数据，判断数组中是否有当前勾选的规格
      for(var i in this.specificationItems){
        var obj = this.specificationItems[i];
        if(obj.attributeName == specName){
          //当前勾选的规格在数组中已经存在了，需要判断当前勾选的选项是否存在
          var index = obj.attributeValue.indexOf(optionName);
          if(index >= 0){
            //当前勾选的选项值在数组中存在
            obj.attributeValue.splice(index, 1);
            if(obj.attributeValue.length==0){
              this.specificationItems.splice(i,1);
            }
          }else{
            //当前勾选的选项值在数组中不存在
            obj.attributeValue.push(optionName)
          }
          this.generateList();
          return;
        }
      }

      //当前勾选的规格在数组中不存在
      this.specificationItems.push({"attributeName":specName,attributeValue:[optionName]})
      this.generateList();
    },
    generateList(){
      var items = [{spec:{}}];
      var result = [];

      for(var i in this.specificationItems){
        var specObj = this.specificationItems[i];
        for(var j in specObj.attributeValue){
          var optionValue =  specObj.attributeValue[j];
          for(var k in items){
            var baseObj = items[k]
            //复制基础对象
            var copyObj = JSON.parse(JSON.stringify(baseObj));
            copyObj.spec[specObj.attributeName] = optionValue;
            result.push(copyObj);
          }
        }
        //当前规格交叉结束
        items = result;
        result = [];
      }

      this.items = items;
    },
    removeImg(obj){
      var index = this.imageList.indexOf(obj);
      this.imageList.splice(index,1);
    }
  },
  watch:{

    "value": function (newValue, oldVal) {
      this.form.goods.category1Id = newValue[0];
      this.form.goods.category2Id = newValue[1];
      this.form.goods.category3Id = newValue[2];

      getCategory(newValue[2]).then((res)=>{
        this.form.goods.typeTemplateId = res.data.typeId
      })
    },

    // "form.goods.category1Id": function (newValue, oldVal) {
    //   this.form.goods.category2Id = ''
    //   this.form.goods.category3Id = ''
    //   this.category3List = []
    //
    //   listCategory({parentId: newValue}).then((res) => {
    //     this.category2List = res.rows
    //   })
    // },
    // "form.goods.category2Id": function (newValue, oldVal){
    //   this.form.goods.category3Id = ''
    //   if(newValue != ''){
    //     listCategory({parentId:newValue}).then((res)=>{
    //       this.category3List = res.rows
    //     })
    //   }
    // },
    // "form.goods.category3Id": function (newValue, oldVal){
    //   if(newValue == ''){
    //     this.form.goods.typeTemplateId = ''
    //     return;
    //   }
    //
    //   getCategory(newValue).then((res)=>{
    //     this.form.goods.typeTemplateId = res.data.typeId
    //   })
    // },
    "form.goods.typeTemplateId":function (newValue, oldVal){
      if(newValue == ''){
        this.form.goods.brandId = ''
        this.brandList = []
        this.specList = []
        return;
      }

      getTemplate(newValue).then((res)=>{
        this.brandList = JSON.parse(res.data.brandIds)
        this.customAttributeItemsList = JSON.parse(res.data.customAttributeItems)
        this.specList = JSON.parse(res.data.specIds)

        for(var i in this.specList){
          var spec = this.specList[i];
          this.getOptions(spec.id);
        }
      })
    }
  },
  created() {
    this.token = 'Bearer '+Cookies.get("Admin-Token")


    listTreeCategory().then((res)=>{
      this.options = res.rows
    })


    listCategory({parentId:0}).then((res)=>{
      this.category1List = res.rows
    })
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
